package com.example.datacollection.controller;

import com.example.datacollection.bean.DataDemography;
import com.example.datacollection.constants.PopulationConstants;
import com.example.datacollection.service.JsoupTestService;
import com.example.datacollection.service.PopulationService;
import com.example.datacollection.service.RateService;
import com.example.datacollection.service.impl.PopulationCollection;
import com.example.datacollection.service.impl.RateCollection;
import com.example.datacollection.service.impl.SumCollection;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class testController {
    @Autowired
    private PopulationService populationService;
    @Autowired
    private RateService rateService;
    @Autowired
    private PopulationCollection populationCollection;
    @Autowired
    private RateCollection rateCollection;


    @PostMapping("populationList")
    public DataDemography populationList() {
        List<DataDemography> dataDemographies = populationService.selectPopulationList();
        System.out.println(dataDemographies);
        return dataDemographies.get(0);
    }

    @GetMapping("population")
    public String populationController(String url) {
        if (StringUtils.isNotEmpty(url)) {
            String result = populationService.populationCollection(url);
            return result;
        } else {
            return PopulationConstants.REQUESTPATH_IS_EMPTY;
        }
    }

    @GetMapping("rate")
    public String rateController(String url) {
        if (StringUtils.isNotEmpty(url)) {
            String result = rateService.rateCollection(url);
            return result;
        } else {
            return PopulationConstants.REQUESTPATH_IS_EMPTY;
        }
    }

    @GetMapping("collectionThreads")
    public String collectionThreadsController() {
        List<SumCollection> collectionThreads = new ArrayList<>();
        collectionThreads.add(populationCollection);
        collectionThreads.add(rateCollection);
        // 创建一个固定数量线程池
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < collectionThreads.size(); i++) {
            final int index = i;
            fixedThreadPool.execute(() -> collectionThreads.get(index).collection());
        }
        return "完成";
    }

}
